<?php
namespace app\servergoods\logic;

use \app\manage\logic\BaseLogic;

// 商品分类微应用下的逻辑层
// dbXXXX : 不作为接口返回json数据，用于内部调用
class GoodsCategory extends BaseLogic
{
	protected $name = 'goods_category';
    protected $config = 'db_config_goods';
    protected $goodsCateLogic = '\app\servergoods\logic\GoodsCategory';
    protected $goodsCateModel = '\app\servergoods\model\GoodsCategory';
    protected $goodsCateAttrsModel = '\app\servergoods\model\GoodsCategoryAttrs';
    protected $allowField = ['other_app_read'=>'','is_public'=>0,'name'=>' ','cate_attrs'=>[],'profile_pic'=>'','keywords'=>'','description'=>'','order'=>100];

    use \app\serveruser\traits\addAppId;
    use \app\servergoods\traits\UpdateCate;
    //添加商品分类
    public function addGoodsCate($data): array
    {
    	$res = $this->model($this->goodsCateModel)->save($data);
    	return auto_return($res);
    }
    //前台简单获取某商品分类信息
    public function frontOneCate($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 1;

        if(isset($data['app_id'])){   
            $manageAppId = \app\manage\service\ApiBase::getAppId();
            $_whereOr = $manageAppId == $data['app_id'] ? true : '`app_id`=' . $data['app_id'] . ' OR FIND_IN_SET(' . $data['app_id'] . ',`other_app_read`) OR is_public = 1';
        }else{
            $_whereOr = true;
        }

        $res = $this->model($this->goodsCateModel)
                    ->where($_where)
                    ->where($_whereOr)
                    ->find();
        $res && $res = $res->toArray();
        return auto_return($res);
    }
    //根据id获取该商品分类信息
    public function oneCateInfo($data): array
    {
        $_where['id'] = $data['id'];
        $_where['status'] = ['neq',-1];
        //$_where = $this->_addAppId($_where, $data['app_id']);
        //app_id的筛选
        if(isset($data['app_id'])){   //若卖家查看商品详情，则不传入app_id
            $manageAppId = \app\manage\service\ApiBase::getAppId();
            $_whereOr = $manageAppId == $data['app_id'] ? true : '`app_id`=' . $data['app_id'] . ' OR FIND_IN_SET(' . $data['app_id'] . ',`other_app_read`) OR is_public = 1';
        }else{
            $_whereOr = true;
        }

     	$res = $this->model($this->goodsCateModel)
                    ->where($_where)
                    ->where($_whereOr)
    				->find();
        $res && $res = $res->toArray();

        $parentAttrs = $this->parentAllAttrs(['pid'=>$res['pid'],'app_id'=>$data['app_id']]);
        $allAttrId = $res['cate_attrs_array'] ? array_unique(array_merge($parentAttrs['res'],$res['cate_attrs_array'])) : $parentAttrs['res'];
        $allAttrInfo = logic('\app\servergoods\logic\GoodsCategoryAttrs')->dbAttrsList(['id'=>['in',$allAttrId]],['id','name','en_name','attr_type','attr_values','default_value','status']);
        foreach ($allAttrInfo as $k => &$v) {
            $v['isParent'] = in_array($v['id'], $parentAttrs['res']) ? true : false;   //是否属于父类中的属性
            $v['attr_values'] && $v['attr_values'] = explode(",", $v['attr_values']);
        }
        $res && $res['allAttrInfo'] = $allAttrInfo;
        $res && $res['cate_attrs_array'] = $allAttrId;
        return auto_return($res);
    }
    //内部db查询某分类信息
    public function dbOneCateInfo($data)
    {
        $_where['id'] = $data['id'];
        $_where['status'] = isset($data['status']) ? $data['status'] : ['neq', -1];
        return $this->db()
                    ->where($_where)
                    ->find();
    }
    /*内部获取不包含公共分类的所有分类列表 查询结果可用于操作*/
    public function dbCateList($map = [])
    {
        isset($map['id']) && $_where['id'] = $map['id'];
        isset($map['pid']) && $_where['pid'] = $map['pid'];
        if(isset($map['app_id'])){
            $isManageAppId = $this->_isManageAppId($map['app_id']);
            !$isManageAppId && $_where['app_id'] = $map['app_id'];
        }
        $_where['status'] = ['neq',-1];
        return $this->db()
                    ->where($_where)
                    ->select();
    }

    /*内部获取包含公共分类的所有分类列表  仅查询不用于操作*/
    public function dbAllCateList($map = [])
    {
        isset($map['id']) && $_where['id'] = $map['id'];
        isset($map['pid']) && $_where['pid'] = $map['pid'];
        $_recommendWhere = isset($map['recommend']) ? 'FIND_IN_SET(\'' . $map['recommend'] . '\',`recommend`)' : true;
        $_where['status'] = isset($map['status']) ? $map['status'] : ['neq',-1];

        if(isset($map['app_id'])){   //若卖家查看商品详情，则不传入app_id
            $manageAppId = \app\manage\service\ApiBase::getAppId();
            $_whereOr = $manageAppId == $map['app_id'] ? true : '`app_id`=' . $map['app_id'] . ' OR FIND_IN_SET(' . $map['app_id'] . ',`other_app_read`) OR is_public = 1';
        }else{
            $_whereOr = true;
        }
        if(isset($map['limit']) && $map['limit']){
            $res = $this->db()
                    ->where($_where)
                    ->where($_recommendWhere)
                    ->where($_whereOr)
                    ->limit($map['limit'])
                    ->order('`order` ASC, `id` ASC')
                    ->select();
        }else{
            $res = $this->db()
                    ->where($_where)
                    ->where($_recommendWhere)
                    ->where($_whereOr)
                    ->order('`order` ASC, `id` ASC')
                    ->select();
        }
        return $res;
    }

    /*根据cate_id获取其所有父类的集合<通过审核的>*/
    public function getParentIds($data)
    {
        //cate_id加上父级的cate_id,前后有“,”
        $list = $this->dbAllCateList(['status'=>1]);
        $ids     = $data['cate_id'];
        $params  = '';
        $parentIds = parent_ids($list,$ids,$params,$data['cate_id'],0,'pid','id','');
        $ids = explode(",", $ids);
        foreach ($ids as $k => &$v) {
            $v = (int)$v;
        }
        array_splice($ids, array_search(0, $ids), 1);
        return "," . implode($ids, ",") . ",";
    } 

    /*
        根据id数组 启用/禁用一个或多个分类
        父类被禁用，则其所有子类也被禁用，开启同理
    */
    public function changeCateStatus($data): array
    {
        $list = $this->dbCateList(['app_id'=>$data['app_id']]);
    	$saveData['status'] = $data['status'];

        foreach ($data['id'] as $k => $v) {
            $childId = child_ids($list, $v, 'id', 'pid', 'id');  //使用static数组 获取该分类下的所有子类
        }
        $data['id'] = array_merge($childId, $data['id']);
        $_where['id'] = ['in',$data['id']];
        $_where = $this->_addAppId($_where, $data['app_id']);
        
    	$res = $this->model($this->goodsCateModel)->save($saveData, $_where);
        return auto_return($res);
    }
    //删除一个或多个商品分类
    public function delCate($data): array
    {
        $map['pid'] = ['in',$data['id']];
        $map = $this->_addAppId($map, $data['app_id']);

        $list = $this->dbCateList($map);
        if(count($list) > 0){
            return auto_failure(null,'失败，存在子类'.$list[0]['name']);
        }
        $_where['id'] = ['in',$data['id']];
        $_where['status'] = ['in',['0','1']];
        $_where = $this->_addAppId($_where, $data['app_id']);
        $update['status'] = -1;
        $res = $this->db()
                    ->where($_where)
                    ->update($update);
        return auto_return(1,'删除成功','删除失败');
    }
    //修改商品分类  子类与父类分开修改
    //父类修改other_app_read时，子类陪同
    //父类与子类可修改字段不一样
    public function editGoodsCate($data): array
    {
        return $this->_updateCate($this->goodsCateLogic, $this->goodsCateModel, $data, 'dbCateList', 'dbOneCateInfo');
    }
    //获取商品分类列表
    public function _goodsCateList($data, bool $isFront = false): array 
    {
        $_where = $this->_addAppId([], $data['app_id']);
        $isFront && $_where['status'] = 1;
        if(isset($data['recommend']) && $data['recommend']){
            $_where['recommend'] = $data['recommend'];
        }
        $list = $this->dbAllCateList($_where);
        foreach ($list as $k => &$v) {
            $v['status_text'] = $v['status'] ? '正常' : '禁用';
        }
        $list = list_to_tree($list,'id','pid','_child',$data['id']);
        return auto_return($list);
    }

    //后台获取商品分类列表
    public function goodsCateList($data): array
    {
        return $this->_goodsCateList($data);
    }

    //前台获取商品分类列表
    public function frontGoodsCateList($data): array 
    {
        return $this->_goodsCateList($data, true);
    }

    //前台获取某商品父类下的推荐商品子类分类（多级树状）
    public function recommendCateList($data): array 
    {
        $_where['app_id'] = $data['app_id'];
        //$_where['pid'] = $data['pid'];
        $_where['limit'] = $data['limit'];
        $_where['recommend'] = $data['recommend'];
        $_where['status'] = 1;
        $list = $this->dbAllCateList($_where);
        $list = list_to_tree($list,'id','pid','_child',$data['pid']);
        return auto_return($list, '成功获取商品分类列表');
    }

    /*管理员推荐某个商品分类*/
    public function recommend($data): array 
    {
        $_where['id'] = $data['id'];
        $_where['status'] = 1;
        $_where = $this->_addAppId($_where, $data['app_id']);
        $saveData['recommend'] = trim($data['recommend'], ",");
        //追加式推荐
        /*if($data['recommend'] == ''){
            $saveData['recommend'] = $data['recommend'];
        }else{
            //追加推荐位
            $cateInfo = $this->model($this->goodsCateModel)->where($_where)->find();
            $saveData['recommend'] = $cateInfo['recommend'] ? implode(",", array_unique(array_merge(explode(",", $cateInfo['recommend']), explode(",", $data['recommend'])))) : $data['recommend'];
        }*/
        $res = $this->model($this->goodsCateModel)->save($saveData, $_where);
        return auto_return($res);
    }

    /*内部获取某分类下的所有属性合集*/
    protected function _parentAllAttrs(Array $data): array 
    {
        $_where['app_id'] = $data['app_id'];
        $_where['status'] = 1;
        $list = $this->dbAllCateList($_where);
        $ids = $data['id'];
        $params = '';
        $resData = parent_ids($list, $ids, $params, $data['id'], 0, 'pid', 'id', 'cate_attrs');
        $res = $resData['cate_attrs'] ? array_unique( explode(',', $resData['cate_attrs']) ) : [];
        return $res;
    }

    //获取该父类的所有属性合集
    public function parentAllAttrs(Array $data): array
    {
        $getAttrWhere['app_id'] = $data['app_id'];
        $getAttrWhere['id'] = $data['pid'];
        $attrList = $this->_parentAllAttrs($getAttrWhere);
        return auto_return($attrList, '成功获取该分类所有属性');
    }

    /*前台获取该商品分类下的参与搜索的商品属性列表*/
    public function getCateFilterAttr($data): array 
    {
        $getAttrWhere['app_id'] = $data['app_id'];
        $getAttrWhere['id'] = $data['id'];
        $attrIds = $this->_parentAllAttrs($getAttrWhere);
        //前台获取参与搜索 正常状态
        $attrWhere['id'] = ['in', $attrIds];
        $attrWhere['is_filter'] = 1;
        $attrWhere['status'] = 1;
        $attrList = $this->model($this->goodsCateAttrsModel)->where($attrWhere)->select();
        return auto_return($attrList, '成功获取该分类所有属性');

    }

    /*前台获取该商品分类的所有分类（面包屑）*/
    public function getParentCate($data): array 
    {
        $list = $this->dbAllCateList(['status'=>1, 'app_id'=>$data['app_id']]);
        $ids  = $data['id'];
        $params  = '';
        $parent = array_reverse(parent_ids($list,$ids,$params,$data['id'],0,'pid','id','id'));
        $parentInfo = $this->model($this->goodsCateModel)->where('id','in',$parent['id'])->select();
        return auto_return($parentInfo);
    }
}
